package person.drf.shop.product.jucTest;


import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoReDemo {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3); //模拟资源类，有3个空车位

        //  6个线程，抢三个车位
        for (int i = 1; i <=  6; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"---抢到了车位");
                    TimeUnit.SECONDS.sleep(3);  //  停三秒
                    System.out.println(Thread.currentThread().getName()+"---离开了了车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                finally {
                    semaphore.release();  //释放车位
                }

            },String.valueOf(i)).start();
        }
    }
}
